package com.example.hzit.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hzit.entity.LoginUser;
import com.example.hzit.entity.User;
import com.example.hzit.service.UserService;
import com.example.hzit.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
* @author liujuntao
* @description 针对表【TbUser】的数据库操作Service实现
* @createDate 2025-01-16 09:39:12
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    /**
     * 验证是否登录，登录就返回用户
     * @param username
     * @param password
     * @return
     */
    @Override
    public LoginUser findById(String username, String password) {
        LoginUser loginUser = new LoginUser();
        // 1.1 根据用户名得到用户对象
        User user = this.getOne(new QueryWrapper<User>().eq("username", username));
        // 1.2 将传入的密码进行md5加密再与数据库中的密码进行比较，如果相等，证明有此用户
        if(!Objects.isNull(user)){
            if(StrUtil.isNotBlank(password)) {
                String pwd = SecureUtil.md5(password);
                if(pwd.equals(user.getPassword())){
                    loginUser.setUser(user);
                    loginUser.setUserId(user.getId().toString());
                    return loginUser;
                }
            }
        }
        
        return null;
    }
    
    @Override
    public boolean saveUserMsg(User user) {
        if(!Objects.isNull(user)){
            if(StrUtil.isNotBlank(user.getPassword())) {
                String pwd = SecureUtil.md5(user.getPassword());
                user.setPassword(pwd);
            }
        }
        boolean i = this.save(user);
        return i;
    }
}




